package com.huabo.system.controller;


import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
import com.hbfk.util.JsonBean;
import com.hbfk.util.ResponseFormat;
import com.huabo.system.oracle.entity.TblPersonalTrain;
import com.huabo.system.oracle.entity.TblStaff;
import com.huabo.system.service.TblJobService;
import com.huabo.system.service.TblOrganizaService;
import com.huabo.system.service.TblStaffService;
import com.huabo.system.utils.DesUtil;
import com.huabo.system.utils.SHAUtil;
import com.huabo.system.utils.StringUtil;

import cn.hutool.http.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSON;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.InvalidKeySpecException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@Slf4j
@Api(value = "组织架构同步Controller", tags = {"组织架构同步"})
public class HumanResourcesSynchronizationController {
    private static final Log logger = LogFactory.getLog(HumanResourcesSynchronizationController.class);
    public static ResourceBundle hr = ResourceBundle.getBundle("setting/humanResources");

    
    @Resource
	private TblStaffService tblStaffService;
	
	@Resource
	private TblJobService  tblJobService;
	
	@Resource
	private TblOrganizaService TblOrganizaService;
	
	
//	  @RequestMapping(value = "/getToken", method = {RequestMethod.POST})
//	  @ApiParam(value = "获取开发者认证dev_token")
//	  public String getToken(HttpServletRequest request) {
//			org.apache.commons.httpclient.HttpClient client=new org.apache.commons.httpclient.HttpClient();
//			org.apache.http.HttpResponse reponse=null;
//			String token="";
//			try {
//			 PostMethod postMethod=new PostMethod(hr.getObject("tokenUrl").toString());
//			 com.alibaba.fastjson.JSONObject obj=new com.alibaba.fastjson.JSONObject();
//			obj.put("dev_account",hr.getObject("dev_account").toString()); //
//			obj.put("dev_password",hr.getObject("dev_password").toString());
//			postMethod.setRequestHeader("Content-Type","application/json");
//			RequestEntity entity = new StringRequestEntity(obj.toString(),"application/json","UTF-8");
//			postMethod.setRequestEntity(entity);
//			client.executeMethod(postMethod);
//			  java.io.InputStream in = postMethod.getResponseBodyAsStream();
//			//下面将stream转换为String
//			StringBuffer sb = new StringBuffer();
//			InputStreamReader isr = new InputStreamReader(in, "UTF-8");
//			char[] b = new char[4096];
//			for(int n; (n = isr.read(b)) != -1;) {
//			            sb.append(new String(b, 0, n));
//			        }
//		    String   result = sb.toString();
//		    System.out.println(result);
//		    JSONObject json=JSONObject.fromObject(result);
//			if(json.get("success").equals("true")){
//				JSONObject msg=JSONObject.fromObject(json.get("msg"));
//				token=msg.getString("dev_token");
//			}
//		} catch (Exception e) {
//			// TODO: handle exception
//			e.printStackTrace();
//		}finally {
//		}
//			return token;
//		}
	 /**
     * 获取管理员id
     * @param token
     * @return
     */
    public static String getAdminId(String token) {
        Map<String, String> params = new HashMap<>();
        params.put("dev_token", token);
        String result = doGet("api/org.do?method=findAdmin", params);
        JSONObject msg = getResultMsg(result);
        if (msg != null) {
            JSONArray jsonArray = msg.getJSONArray("persons");
            if (jsonArray.size() > 0) {
                JSONObject adminJson = jsonArray.getJSONObject(0);
                return adminJson.getString("id");
            }
        }
        return null;
    }
	
	 @RequestMapping(value = "/postJob", method = {RequestMethod.POST})
	  @ApiParam(value = "同步岗位")
	  public String postJob(HttpServletRequest request) {
			try {
		        String token = getToken(hr.getObject("dev_account").toString(), hr.getObject("dev_password").toString());
		        String userId = getUserId(hr.getObject("phone").toString(), token);
			        Map<String, String> params = new HashMap<>();
			        params.put("dev_token", token);
			        params.put("user_id",userId);
			        params.put("dev_login_type","PHONE");
			        params.put("includeDeleteData","");
			        String result = doGet(hr.getObject("JobUrl").toString(), params);
			        tblJobService.syncJob(result);
			        return result;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
		}
			return "";
		}
	 
	  @RequestMapping(value = "/postOrg", method = {RequestMethod.POST})
	  @ApiParam(value = "同步部门")
	  public String postOrg(HttpServletRequest request) {
		try {
			String token = getToken(hr.getObject("dev_account").toString(), hr.getObject("dev_password").toString());
			String userId = getUserId(hr.getObject("phone").toString(), token);
			Map<String, String> params = new HashMap<>();
			params.put("dev_token", token);
			params.put("user_id", userId);
			params.put("dev_login_type", "PHONE");
			params.put("parentId", "1");
			params.put("includeChildren", "true");
			params.put("includeSelf", "true");
			String result = doPost(hr.getObject("orgUrl").toString(), params);
			TblOrganizaService.syncOrg(result);
			return result;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
			 return "";
		}
	  
	@RequestMapping(value = "/postPerson", method = { RequestMethod.POST })
	@ApiParam(value = "同步人员")
	public String postPerson(HttpServletRequest request) {
		String result="";
		try {
			String token = getToken(hr.getObject("dev_account").toString(), hr.getObject("dev_password").toString());
			String userId = getUserId(hr.getObject("phone").toString(), token);
			Map<String, Object> params = new HashMap<>();
			params.put("user_id", userId);
			params.put("dev_login_type", "PHONE");
			String data = doPost(hr.getObject("personUrl").toString()+"&dev_token="+token+"&user_id="+userId+"&dev_login_type=PHONE&pageIndex=1&pageSize=90", null);
			net.sf.json.JSONObject paramStr = net.sf.json.JSONObject.fromObject(data);
			net.sf.json.JSONObject msg = net.sf.json.JSONObject.fromObject(paramStr.get("msg").toString());
			if(paramStr.get("success").toString()=="true"){
			int totalpage=Integer.valueOf(msg.get("totalPage").toString());
			int total=Integer.valueOf(msg.get("total").toString());
            for(int i=1;i<=totalpage;i++){
            	getPerson(token,userId,i);
			}
			}
			return result;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
		}
		return "";
	}
	public String getPerson(String token,String userId,int pageIndex) throws Exception{
		String data = doPost(hr.getObject("personUrl").toString()+"&dev_token="+token+"&user_id="+userId+"&dev_login_type=PHONE&pageIndex="+pageIndex+"&pageSize=90", null);
		try {
			tblStaffService.syncPerson(data);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} 
		
		return data;
	}
	  
	   public static String addParams(String url, String token, String userId) {
	        if (StringUtil.isNotEmpty(token)) {
	            url += "&dev_token=" + token;
	        }
	        if (StringUtil.isNotEmpty(userId)) {
	            url += "&user_id=" + userId;
	        }
	        return url;
	    }

	  
	  
	    public static String getUserId(String personId, String token) {
	        if (StringUtil.isEmpty(personId)) {
	            throw new IllegalArgumentException("需要加密成userId的种子码不能为空");
	        }
	        try {
	            return DesUtil.encode(personId, token + hr.getObject("dev_password").toString());
	        } catch (InvalidKeyException e) {
	            e.printStackTrace();
	        } catch (NoSuchAlgorithmException e) {
	            e.printStackTrace();
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();
	        } catch (NoSuchProviderException e) {
	            e.printStackTrace();
	        } catch (NoSuchPaddingException e) {
	            e.printStackTrace();
	        } catch (IllegalBlockSizeException e) {
	            e.printStackTrace();
	        } catch (BadPaddingException e) {
	            e.printStackTrace();
	        } catch (InvalidKeySpecException e) {
	            e.printStackTrace();
	        }
	        return null;
	    }
	    
	    public static String getToken(String devUser, String devPass) {
	        Map<String, String> params = new HashMap<>();
	        params.put("grant_type", "client_credentials");//认证模式
	        params.put("dev_account", devUser);//开发帐号
	        params.put("dev_password", SHAUtil.SHA1(devPass));//开发者密码
	        String result = doPost("api/auth.do?method=token", params);
	        if (StringUtil.isNotEmpty(result)) {
	            JSONObject msg = getResultMsg(result);
	            String devToken = msg.getString("dev_token");
	            //{"errcode":0,"msg":{"dev_token":"f1ee5f87-c954-4dca-8b24-c4ebbc8377f2","expires_in":7200},"async":false,"success":true,"waitSecond":0}
	            return devToken;
	        }
	        return null;
	    }
	    
	    public static JSONObject getResultMsg(String result) {
	        if (StringUtil.isNotEmpty(result)) {
	            JSONObject json = com.alibaba.fastjson.JSON.parseObject(result);
	            return json.getJSONObject("msg");
	        }
	        return null;
	    }


	    public static String doPost(String url, Map<String, String> params) {
	        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
	        // 创建Post请求
            HttpPost httpPost = new HttpPost(hr.getObject("serverUrl").toString() + url);
	        String paramStr = JSONObject.toJSONString(params);
	        StringEntity entity = new StringEntity(paramStr, "UTF-8");
	        httpPost.setEntity(entity);
	        // 响应模型
	        CloseableHttpResponse response = null;
	        try {
	            // 由客户端执行(发送)Post请求
	            response = httpClient.execute(httpPost);
	            // 从响应模型中获取响应实体
	            HttpEntity responseEntity = response.getEntity();

	            System.out.println("响应状态为:" + response.getStatusLine());
	            if (responseEntity != null) {
	                String responseStr = EntityUtils.toString(responseEntity);
	                System.out.println("响应内容为:" + responseStr);
	                return responseStr;
	            }
	            return null;
	        } catch (ClientProtocolException e) {
	            e.printStackTrace();
	        } catch (ParseException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                // 释放资源
	                if (httpClient != null) {
	                    httpClient.close();
	                }
	                if (response != null) {
	                    response.close();
	                }
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }

	        return null;
	    }

	    public static String doGet(String url, Map<String, String> params) {
	        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
	        CloseableHttpResponse response = null;
	        try {
	            if (params != null) {
	                StringBuilder urlBuilder = new StringBuilder(url);
	                for (String key : params.keySet()) {
	                    urlBuilder.append("&").append(key).append("=").append(params.get(key));
	                }
	                url = urlBuilder.toString();
	            }
	            HttpGet httpGet = new HttpGet(hr.getObject("serverUrl").toString() + url);
	            // 由客户端执行(发送)Get请求
	            response = httpClient.execute(httpGet);
	            // 从响应模型中获取响应实体
	            HttpEntity responseEntity = response.getEntity();
	            System.out.println("响应状态为:" + response.getStatusLine());
	            if (responseEntity != null) {
	                String responseStr = EntityUtils.toString(responseEntity);
	                System.out.println("响应内容为:" + responseStr);
	                return responseStr;
	            }
	            return null;
	        } catch (ClientProtocolException e) {
	            e.printStackTrace();
	        } catch (ParseException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                // 释放资源
	                if (httpClient != null) {
	                    httpClient.close();
	                }
	                if (response != null) {
	                    response.close();
	                }
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	        return null;
	    }
	    

	    //人力资源同步
	      @RequestMapping(value = "/syncinterface/syncUser", method = {RequestMethod.POST})
	      @ApiOperation(value = "人力资源信息系统--人员同步")
	      public Map<String, Object> saveorupdate(HttpServletRequest request,
	      		@ApiParam(name="operaType",value="操作类型 0 -新增、1-修改、2-启用弃用",required=true)Integer operaType,
	      		@ApiParam(name="data",value="推送人员集合",required=true)@RequestParam(value="data", required = true)String data) {
	      	Map<String, Object> resultMap = new HashMap<String, Object>(0);
	  		try {
	  			resultMap = this.tblStaffService.syncUser(operaType, data);
	  		} catch (Exception e) {
	  			ResponseFormat.retParam(1,1000,e.getMessage());
	  		}
	  		return resultMap;
	      }
	      
	      @RequestMapping(value = "/syncinterface/syncPost", method = {RequestMethod.POST})
	      @ApiOperation(value = "人力资源信息系统--岗位同步")
	      public  Map<String, Object> syncPost(HttpServletRequest request,
	      		@ApiParam(name="operaType",value="操作类型 0 -新增、1-修改、2-启用弃用",required=true)Integer operaType,
	      		@ApiParam(name="data",value="推送岗位集合",required=true)@RequestParam(value="data", required = true)String data) {
	      	 Map<String, Object> resultMap = new HashMap<String, Object>(0);
	  		try {
	  			resultMap = this.tblJobService.syncPost(operaType, data);
	  		} catch (Exception e) {
	  			ResponseFormat.retParam(1,1000,e.getMessage());
	  		}
	  		return resultMap;
	      }
	      
	      @RequestMapping(value = "/syncinterface/syncAllOrg", method = {RequestMethod.POST})
	      @ApiOperation(value = "人力资源信息系统--部门同步")
	      public  Map<String, Object> syncAllOrg(HttpServletRequest request,
	      		@ApiParam(name="operaType",value="操作类型 0 -新增、1-修改、2-启用弃用",required=true)Integer operaType,
	      		@ApiParam(name="data",value="推送部门集合",required=true)@RequestParam(value="data", required = true)String data) {
	     	 Map<String, Object> resultMap = new HashMap<String, Object>(0);
	  		try {
	  			resultMap = this.TblOrganizaService.syncAllOrg(operaType, data);
	  		} catch (Exception e) {
	  			ResponseFormat.retParam(1,1000,e.getMessage());
	  		}
	  		return resultMap;
	      }
}
